package com.cn.wanxi.filter;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.result.ResultModel;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//过滤器 /*代表后面 的所有
@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        对所有的连接（前端访问后台的接口地址做出判断）
//        得到前端访问的地址？
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String path = req.getServletPath();
        System.out.println(path);
//        判断是否已经登录
        if (!path.startsWith("/back/")) {//拦截
//            放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String username = (String) req.getSession().getAttribute("username");
        if (username == null) {
//                页面重定向
//                resp.sendRedirect("/html/login.html");
            resp.getWriter().println(JSONObject.toJSONString(ResultModel.noLogin()));
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);

    }
}
